<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<script type="text/javascript">
    var context_path = '<%=path%>';
</script>
<div class="row-fluid" id="bind_list_grid-div" style="position:relative;margin-top: 0px;">
	<div id="bind_list_leftdiv" style="background-color:#ffffff; float:left; width:200px;border-right: 1px solid #ccc; box-sizing: border-box; ">
		<div class="row-fluid" style="background-color:#f7f6f6;">
			<i class="fa fa-sitemap" aria-hidden="true" style="margin:10px 5px;"></i>&nbsp;列表展示
		</div>
		<div class="row-fluid" style="overflow: auto">
			<ul id="bind_list_treeDemo" class="ztree"></ul>
		</div>
	</div>
	<!-- 表格内容 -->
	<div style="padding:0;margin:0; float:left; width:calc(100% - 200px); ">
		<!-- 工具栏 -->
		<div class="row-fluid" id="bind_list_table_toolbar" style="padding:5px 6px;">
			<button class="btn btn-primary btn-addQx" onclick="openAddPage();">
				添加<i class="fa fa-plus" aria-hidden="true" style="margin-left:5px;"></i>
			</button>
			<button class="btn btn-primary btn-addQx" onclick="openEditPage();">
				编辑<i class="fa fa-pencil" aria-hidden="true" style="margin-left:5px;"></i>
			</button>
			<button class="btn btn-primary btn-deleteQx" onclick="deleteUser();">
				删除<i class="fa fa-trash" aria-hidden="true"
					style="margin-left:5px;"></i>
			</button>

		</div>
		<!-- 表格 -->
		<div class="row-fluid" style="padding:0 3px;" id="xx">
			<!-- 表格数据 -->
			<table id="bind_list_grid-table"></table>
			<!-- 表格底部 -->
			<div id="bind_list_grid-pager"></div>
		</div>
	</div>

</div>

<script type="text/javascript" src="<%=path%>/plugins/public_components/js/iTsai-webtools.form.js"></script>
<script type="text/javascript">

var name=null;
var ip=null;
var port=null;
var interfaceAuthority = "";
//var selectProjectId = 90;   //工程/货架主键
$.ajax({
    type: "POST",
    url: context_path + "/wmsbind/getInterfaceAuthority?time="+new Date().getTime(),
    dataType: 'json',
    success: function (data) {
        interfaceAuthority=data.interfaceAuthority;
        console.log(interfaceAuthority);
    }
});

$.ajax({
    type: "POST",
    url: context_path + '/wmsbind/getIp',
    dataType: 'json',
    cache: false,
    success: function (data) {
        name = data.name;
        ip = data.ip;
        port = data.port;
        
        console.log(name+","+ip+","+port);
    }
});

    //-----------------初始化树----------------------------
    
var zTree;   //树形对象
var selectTreeId = 0;   //存放选中的树节点id
//树的相关设置
var setting = {
    check: {
        enable: true	
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    edit: {
        enable: false,
        drag:{
        	isCopy:false,
        	isMove:false
        }
    },
    callback: {
		onClick: zTreeOnClick,
		onAsyncSuccess: zTreeOnAsyncSuccess
    },
	async: {
		enable: true,
		url:context_path+"/wmsshevle/treeData",
		autoParam:["id"],
		type: "POST"
	},//异步加载数据
};

/**
 * 获取树中选中节点的id
 * @returns {Number}
 */
function getSelectNodeId(){
	var nodes = zTree.getSelectedNodes();
	var deptid = 0;
	var selectNode = {id:null,atype:0};
	if(nodes.length>0){
		selectNode.id =  nodes[0].id;
		selectNode.atype = nodes[0].atype;
	}
	
	return selectNode;
}

//ztree加载成功之后的回调函数
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	zTree.expandAll(true);
	var datalist = JSON.parse(msg);
	//默认点击第一个
    if(datalist.length>0){
    	console.dir(datalist);
    	var clickNode = zTree.getNodeByParam("id", datalist[0].id, null);
    	clickNode.click = zTreeOnClick(null,null,clickNode);
    	zTree.selectNode(clickNode);
    }
};

//树节点click事件
function zTreeOnClick(event, treeId, treeNode) {
	//节点点击事件 alert(treeNode.tId + ", " + treeNode.name);
	//后台获取相应工程的地图数据
	var selectnodes = zTree.getSelectedNodes();  //选中的节点
	selectTreeId = treeNode.id;   //记录每次点击的树节点
	console.log(treeNode.id+","+treeNode.atype+","+treeNode.name);
	//根据点击的货架，获取货架列表
	$("#bind_list_grid-table").jqGrid('setGridParam',
            {
                postData: {areaId: treeNode.id,atype:treeNode.atype, queryJsonString: ""} //发送数据
            }
    ).trigger("reloadGrid");
};


//初始化树
$.fn.zTree.init($("#bind_list_treeDemo"), setting);
zTree = $.fn.zTree.getZTreeObj("bind_list_treeDemo");

var openWindowIndex = null;

var zhanweiStr = "--";
    //-----------------初始化树----------------------------
    
    
    //----------------------------货架列表---------------------------------------------------
    var oriData;      //表格数据
    var _grid;        //表格对象

    $(function () {
        //初始化表格
        _grid = jQuery("#bind_list_grid-table").jqGrid({
            url: context_path + '/wmsbind/bindList?onlyContainBind='+false,
            datatype: "json",
            postData:{areaId : getSelectNodeId().id,atype :getSelectNodeId().atype},
            colNames: ['关系主键','货架主键', '货架','库位信息',],
            colModel: [
                {name: 'id', index: 'id', width: 30, hidden: true},
                {name: 'stuff_id', index: 'stuff_id', width: 30, hidden: true},
                {name: 'shevelName', index: 'shevelName', width: 150,sortable:false},
                {name: 'allocation', index: 'allocation', width: 150,sortable:false}
            ],
            rowNum: 20,
            rowList: [10, 20, 30],
            pager: '#bind_list_grid-pager',
            altRows: true,
            viewrecords: true,
            caption: "货架列表",
            autowidth: true,
            multiselect: true,
            multiboxonly: true,
            loadComplete: function (data) {
                var table = this;
                setTimeout(function () {
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
                oriData = data;
            },
            emptyrecords: "没有相关记录",
            loadtext: "加载中...",
            pgtext: "页码 {0} / {1}页",
            recordtext: "显示 {0} - {1}共{2}条数据"
        });
        //在分页工具栏中添加按钮
        jQuery("#bind_list_grid-table").navGrid('#bind_list_grid-pager', {
            edit: false,
            add: false,
            del: false,
            search: false,
            refresh: false
        }).navButtonAdd('#bind_list_grid-pager', {
              caption: "",
              buttonicon: "ace-icon fa fa-refresh green",
              onClickButton: function () {
                  $("#bind_list_grid-table").jqGrid('setGridParam',
                          {
                              postData: {areaId : getSelectNodeId().id,atype :getSelectNodeId().atype, queryJsonString: ""} //发送数据
                          }
                  ).trigger("reloadGrid");
              }
          });

        $(window).on('resize.jqGrid', function () {
            $("#bind_list_grid-table").jqGrid('setGridWidth', $("#bind_list_grid-div").width() - 205);
            $("#bind_list_grid-table").jqGrid('setGridHeight', (document.documentElement.clientHeight - 
            $("#bind_list_grid-pager").height() - 195 - (!$(".query_box").is(":hidden") ? $(".query_box").outerHeight(true) : 0) ));
        });

        $(window).triggerHandler('resize.jqGrid');
    });
    
	
	
	/**
	 * 入库单查询功能:获取查询页面中的值，并将值放入列表页面中隐藏的form
	 * @param jsonParam     查询页面传递过来的json对象
	 */
	function queryAreaListByParam(jsonParam) {
	    iTsai.form.deserialize($('#bind_list_hiddenQueryForm'), jsonParam);   //将json对象反序列化到列表页面中隐藏的form中
	    var queryParam = iTsai.form.serialize($('#bind_list_hiddenQueryForm'));
	    var queryJsonString = JSON.stringify(queryParam);         //将json对象转换成json字符串
	    //执行查询操作
	    $("#bind_list_grid-table").jqGrid('setGridParam',
	        {
	    	  postData: {areaId : null,atype :0, queryJsonString: queryJsonString} //发送数据
	        }
	    ).trigger("reloadGrid");
	}
	
	/**
	 * 新增货架
	 */
	function addShevel() {
		 var selecttreeData = getSelectNodeId();
		 if(selecttreeData.id){
			 if(selecttreeData.atype==1){//选择库区可以添加货架
				//打开新增界面
				    Dialog.open({
				        title: "货架添加",
				        width: 650, height: '500',
				        url: context_path + "/wmsbind/addShevel.do?area_id=" + selecttreeData.id,
				        theme: "simple",
				        drag: false,
				        clickMaskToClose: false
				    });
			 }else{
				 Dialog.alert("仓库不可以添加货架！");
			 }
		 }
	}

	/**
	 * 修改区域
	 */
	function editShevel() {
	    var checkedNum = getGridCheckedNum("#bind_list_grid-table", "id");
	    if (checkedNum == 0) {
	        Dialog.alert("请选择一个要编辑的货架！");
	        return false;
	    } else if (checkedNum > 1) {
	        Dialog.alert("只能选择一个货架进行编辑操作！");
	        return false;
	    } else {
	        var areaId = jQuery("#grid-table").jqGrid('getGridParam', 'selrow');
	        Dialog.open({
	            title: "货架编辑",
	            width: 650, height: '500',
	            url: context_path + "/wmsshevle/addShevel.do?id=" + areaId,
	            theme: "simple",
	            drag: false
	        });
	    }
	}
	
	/**
	 * 重新加载列表数据
	 * @param parentTreeId
	 */
	function reloadGridData() {
		$("#bind_list_grid-table").jqGrid('setGridParam',
	        {
	    	  postData: {areaId : getSelectNodeId().id,atype :getSelectNodeId().atype, queryJsonString: ""} //发送数据
	        }
	    ).trigger("reloadGrid");
	}
	
	/**
	 * 显示提示窗口
	 * @param msg   显示信息
	 * @param delay 持续时间,结束之后窗口消失
	 */
	function showTipMsg(msg, delay) {
	    Dialog.tip(msg, {type: "loading", delay: delay});
	}
	
	
	function initLeftH(){
		$("#bind_list_leftdiv").height($(window).height()-$("#user-nav").height()-$("#breadcrumb").height());
		$("#bind_list_treeDemo").css("height",$("#bind_list_grid-div").height()-60);
	}
	initLeftH();
	$(window).on("resize",initLeftH());
	
	
	var $stuffId = null;     //货架主键
	var selectCtrlId = null;  //绑定关系主键
	var $bundlineNumber = null;  //第几个货架
	var $bundNumber = null;    //一个货架上的第几列
	/*打开绑定页面*/
	function openAddPage(){
		$.get(context_path+'/wmsbind/toMainBinds?id='+'-1').done(function(data){
			openWindowIndex = layer.open({
    		    title : "添加库位", 
    	    	type:1,
    	    	skin : "layui-layer-molv",
    	    	area : ['650px', '500px'],
    	    	shade : 0.6, //遮罩透明度
    		    moveType : 1, //拖拽风格，0是默认，1是传统拖动
    		    anim : 2,
    		    content : data,
    		});
        });
	}
	function openEditPage(){
		var checkedNum = getGridCheckedNum("#bind_list_grid-table", "id");
	    if (checkedNum == 0) {
	        layer.alert("请选择一个要编辑的库位信息！");
	        return false;
	    } else if (checkedNum > 1) {
	        layer.alert("只能选择一个库位进行编辑操作！");
	        return false;
	    } else {
	    	var id = jQuery("#bind_list_grid-table").jqGrid('getGridParam', 'selrow');
	    	$.get(context_path+'/wmsbind/toMainBinds?id='+id).done(function(data){
			openWindowIndex = layer.open({
    		    title : "添加库位", 
    	    	type:1,
    	    	skin : "layui-layer-molv",
    	    	area : ['650px', '500px'],
    	    	shade : 0.6, //遮罩透明度
    		    moveType : 1, //拖拽风格，0是默认，1是传统拖动
    		    anim : 2,
    		    content : data,
    		});
        });
	    }
	}
	
	
	//根据行号获取已绑定的位控制器，确定层控制器 
	function getLineAddrBySidAndRow(sid,rowNumber){
		var lineAddr = "";
		$.ajax({
		    type: "POST",
		    url: context_path + "/wmsbind/getLineCtrByLineNumber?time="+new Date().getTime(),
		   	data:{sid : sid,rowNumber : rowNumber},
		    dataType: 'json',
		    async:false,
		    success: function (data) {
		        console.dir(data);
		        if(data.result){
		        	lineAddr = data.msg;
		        }
		    }
		});
		return lineAddr;
	}
	
	function getId(_grid,_key){
	    var idAddr = jQuery(_grid).getGridParam("selarrrow");
	    var ids="";
	    ids=idAddr.join(",");
	    return ids;
	}
	
	
	//解除绑定
	function deleteUser(){
		var selectAmount = getGridCheckedNum("#bind_list_grid-table");
		if(selectAmount==0){
			layer.msg("请选择一个要删除的库位！",{icon:2});
			return;
		}
		var ids = getId("#bind_list_grid-table","id");   //获取选中行的id
		var rowData = $("#bind_list_grid-table").jqGrid('getRowData',ids);
		var content = "";
		layer.confirm('确定删除？', /*显示的内容*/
		{
		  shift: 6,
		  moveType: 1, //拖拽风格，0是默认，1是传统拖动
		  title:"操作提示",  /*弹出框标题*/
		  icon: 3,      /*消息内容前面添加图标*/
		  btn: ['确定', '取消']/*可以有多个按钮*/
		}, function(index, layero){
			$.ajax({
				url:context_path + "/wmsbind/deleteGoods",
				type:"POST",
				data:{ids : ids},
				dataType:"json",
				success:function(data){
					if(data){
						layer.msg("操作成功!",{icon:1});
						//刷新用户列表
						reloadGridData();
						layer.close(index);
					}else{
						layer.msg("操作失败!",{icon:2});
					}
			   }
			});
			
		}, function(index){
		  //取消按钮的回调
		  layer.close(index);
		});
	}
</script>

